package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.common.util.common.DictionaryUtil;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.RedisUtil;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.common.CommonPlugIn;
import com.settlement.system.model.entity.common.SystemUser;
import com.settlement.system.model.entity.common.TblCostWeightSummary;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblCostWeightRecordService;
import com.settlement.system.service.ITblCostWeightSummaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 【RR-费用分配权数】菜单 的 【发退货汇总】页签 前端控制器
 *
 * @author xiaochuan
 * @since 2022-12-28
 */

@Slf4j
@Api(tags = "【RR-费用分配权数】菜单 的 【发退货汇总】页签", description = "【RR-费用分配权数】菜单 的 【发退货汇总】页签")
@RestController
@RequestMapping("/tblCostWeightSummary")
public class TblCostWeightSummaryController extends BaseController<TblCostWeightSummary> {

    private ExecutorService executors = Executors.newFixedThreadPool(1);

    @Resource
    private ITblCostWeightSummaryService tblCostWeightSummaryService;

    @Resource
    private ITblCostWeightRecordService tblCostWeightRecordService;

    @Autowired


    @Resource
    private DictionaryUtil dictionaryUtil;


    @Override
    public IBaseService init() {
        return tblCostWeightSummaryService;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        String nameShort = dictionaryUtil.getNameShortShowChildBrandName();
        if (StringUtils.isNotEmpty(nameShort)) {
            model.put("nameShort", nameShort);
        }
        SysUserDetails user = SecurityUtils.getUser();
        model.put("createUser", user.getUsername());
        model.put("updateUser", user.getUsername());
        FasUtil.formatInQueryCondition(model, "channelNo", "companyNo", "accountingPeriod", "shopNo", "nameShort");
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        result.put("foot", tblCostWeightSummaryService.getFoot(model));
    }

    @ApiOperation("获取数据")
    @RequestMapping(value = "getData", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse getData(HttpServletRequest request, @RequestBody Map<String, Object> model) throws ServiceException {
        Map<String, Object> result = new HashMap<>(16);
        try {
            String nameShort = dictionaryUtil.getNameShortShowChildBrandName();
            if (StringUtils.isNotEmpty(nameShort)) {
                model.put("nameShort", nameShort);
            }

            SysUserDetails user = SecurityUtils.getUser();
            Map<String, Object> params = new HashMap<>(model);
            Map<String, Object> params2 = new HashMap<>(params);
            params.put("createUser", user.getUsername());
            params.put("updateUser", user.getUsername());
            FasUtil.formatInQueryCondition(params, "channelNo", "companyNo", "nameShort", "accountingPeriod");

            String verifition = verifyRequest(model);
            if (!StringUtils.isEmpty(verifition)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), verifition);
            }

            boolean ifCanRun = RedisUtil.checkBeforeStart(TblCostWeightSummaryController.class.getName());
            if (!ifCanRun) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "已有操作进行中，请稍后再试");
            }
            //校验 用户选择的 [渠道+会计期间+权数类型]条件 是否存在数据，若存在数据，则不允许 重复获取数据；
            int existsCount = tblCostWeightSummaryService.selectCount(params);
            if (existsCount > 0) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "已存在数据，不允许 重复获取数据；");
            }

            params.put("channelNo", params2.get("channelNo"));
            params.put("companyNo", params2.get("companyNo"));
            params.put("accountingPeriod", params2.get("accountingPeriod"));
            String s = tblCostWeightSummaryService.saveData(params);
            if (StringUtils.isNotEmpty(s)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), s);
            }

            return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
        } catch (Exception ex) {
            log.error("获取数据出错", ex);
            throw new ServiceException("获取数据失败！", ex);
        }
    }


    private String verifyRequest(Map<String, Object> params) {
        return null;
    }


    @ApiOperation("删除数据")
    @RequestMapping(value = "deleteByParams", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse deleteByParams(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            SysUserDetails user = SecurityUtils.getUser();;
            Map<String, Object> params = new HashMap<>(model);
            params.put("createUser", user.getUsername());
            params.put("updateUser", user.getUsername());

            String message = tblCostWeightSummaryService.checkBeforeDelete(model);
            if (StringUtils.isEmpty(message)) {
                Future<?> f = executors.submit(() -> {
                    try {
                        tblCostWeightSummaryService.deleteByParams(params);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);

                        throw new RuntimeException(e);
                    }
                });
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("获取权数中的会计期间")
    @RequestMapping("selectExistAccountPeriod")
    public ObjectDataResponse selectExistAccountPeriod() {
        Map<String, Object> result = new HashMap<>(16);
        try {
            List<CommonPlugIn> rows = tblCostWeightSummaryService.selectExistAccountPeriod();
            result.put("rows", rows);
            result.put("total", rows.size());
            return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            return new ObjectDataResponse(500, "获取列表失败，请联系管理员！");
        }
    }

}

